<?php 
 class CartController extends CommonController{
   
    private $uid=null;
     public function __init(){
    // 为了不覆盖父类CommonController的__init()方法
      parent::__init();
      //  if(!isset($_SESSION['uid']) || !isset($_SESSION['username'])){
     
      // $this->success('您还没有登录，请先登录',U('User/login'),0);
    
     if(isset($_SESSION['uid']) || isset($_SESSION['username'])){
           $this->uid=$_SESSION['uid'];
     
     }
 }




   // 购物车页显示
 public function index(){
   if(isset($_SESSION['cart'])){
      $cart= $_SESSION['cart'];
      $this->assign('cart',$cart['total']);
      $goods = $cart['goods'];
      $this->assign('goods',$goods); 
     $total=cart::getTotalPrice();   //商品总价格
     $this->assign('total',$total);
// p($cart);

   }

 	 $this->display();
 // 
 }

// 添加到购物车
 public function add(){
   if(!IS_AJAX) $this->error('非法请求');
    
    $gid=Q('post.gid',0,'intval'); //商品id
    $num=Q('post.number',0,'intval');
   
  $goods=K('Goods')->where("goods_id={$gid}")->find();

   
    $data=array(
    'id'  =>$gid,//商品id
     'name'=>$goods['goods_name'],
     'num' => $num,
      'price' => $goods['shop_price'], 
      'options' => array(
     
      'goods_img'=>$goods['goods_img']
       )

    );
  cart::add($data);
  $all=Cart::getAllData();
    $d['rows']=$all['total_rows'];
    $d['total']=$all['total'];
// p($all);
  $this->ajax($d);
}


  






// 异步修改购物车
public function edit(){
  $sid=Q('post.sid');
  $shuliang = Q('post.shuliang',0,'intaval');
    if(!IS_AJAX) $this->error('非法请求');    
    $data=array(
    'sid'=>$sid,// 唯一 sid，添加购物车时自动生成 
    'num'=>$shuliang
    ); 
    Cart::update($data);
    $total = $_SESSION['cart']['total'];
    // p($total);
    $this->ajax($total);
}




/**
   * 删除一条
   */
   public function delOne(){
    $sid = Q('post.sid',0,'intaval');
     if(!IS_AJAX) $this->error('非法请求'); 
    // p($sid);die;
    if(!$sid) die('非法操作');
   
    $t = $_SESSION['cart']['total']; //总计
   $subtotal=$_SESSION['cart']['goods'][$sid]['total'];
   $total=$t-$subtotal;  //删除之后的总价
    unset($_SESSION['cart']['goods'][$sid]);
    $data=array(
      'sid'=>$sid,
      'num'=>0
    );
    Cart::update($data);
    $this->ajax($total);   
   }

  /**
   * 清空购物车
   */
  public function delALLCart(){   
     Cart::delAll(); 
    $this->success('清空完成',U('index'));    
  }









}

 ?>